package dk.lector.datasource;

import dk.lector.R;
import dk.lector.domain.TSSystemIntent;
import dk.lector.domain.entities.Document;
import dk.lector.exception.TSMobileException;
import dk.lector.providers.CACHEDDOC_VIEWContentProvider;
import dk.lector.providers.DOC_METADATAContentProvider;
import dk.lector.providers.DOC_STOREDContentProvider;
import dk.lector.providers.FAVORITESContentProvider;
import dk.lector.providers.FavoritesViewContentProvider;
import dk.lector.providers.SEARCHContentProvider;
import dk.lector.providers.SEARCH_RESULTContentProvider;
import dk.lector.providers.SearchViewContentProvider;
import dk.lector.providers.USERContentProvider;
import dk.lector.utils.FileSystemUtil;
import android.content.ContentProviderClient;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.RemoteException;
import android.util.Log;

public class DocDBRepository {

	private static final String TAG = DocDBRepository.class.getSimpleName();
	public static void insertDocMetaData(Context appContext, ContentValues cv) {
		// TODO Auto-generated method stub
		ContentProviderClient client = appContext.getContentResolver()
				.acquireContentProviderClient(
						appContext.getString(R.string.doc_meta_authority));
		try {
			client.insert(DOC_METADATAContentProvider.CONTENT_URI, cv);

		} catch (RemoteException e) {
			throw new TSMobileException(e, DocDBRepository.class,
					"insertDocMetaData()", e.getMessage());
		}

	}

	public static void insertSearchResult(Context appContext, ContentValues sr) {
		ContentProviderClient client = appContext.getContentResolver()
				.acquireContentProviderClient(
						appContext.getString(R.string.search_result_authority));
		try {
			client.insert(SEARCH_RESULTContentProvider.CONTENT_URI, sr);

		} catch (RemoteException e) {
			throw new TSMobileException(e, DocDBRepository.class,
					"insertSearchResult()", e.getMessage());
		}

	}


	public static Uri createSearch(Context appContext, String id, String name) {
		ContentProviderClient client = appContext.getContentResolver()
				.acquireContentProviderClient(
						appContext.getString(R.string.search_authority));
		ContentValues values = new ContentValues();
		values.put(SEARCHContentProvider.SEARCH_DOC_ID, id);
		values.put(SEARCHContentProvider.SEARCH_NAME, name);
		values.put(SEARCHContentProvider.SEARCH_TEXT, "default");
		values.put(SEARCHContentProvider.SEARCH_TIMESTAMP,
				System.currentTimeMillis());

		try {
			Uri uri = client.insert(SEARCHContentProvider.CONTENT_URI, values);
			return uri;
		} catch (RemoteException e) {
			throw new TSMobileException(e, DocDBRepository.class,
					"createSearch()", e.getMessage());
		}

	}

	public static Cursor getSearchResultByUri(Context appContext, Uri uri) {
		// TODO Auto-generated method stub
		return null;
	}

	public static Cursor getSearchByUri(Context appContext, Uri uri) {
		ContentProviderClient client = appContext.getContentResolver()
				.acquireContentProviderClient(
						appContext.getString(R.string.search_authority));

		try {
			return client.query(uri, null, null, null, null);
		} catch (RemoteException e) {
			throw new TSMobileException(e, DocDBRepository.class,
					"createSearch()", e.getMessage());
		}

	}
	public static Cursor getFavorites(Context appContext){
		ContentProviderClient client = appContext.getContentResolver()
				.acquireContentProviderClient(
						"dk.lector.providers.FavoritesViewContentProvider");
		try {
			Cursor c = client.query(FavoritesViewContentProvider.CONTENT_URI,
					null, null, null, null);
			return c;
		} catch (RemoteException e) {
			throw new TSMobileException(e, DocDBRepository.class,
					"getFavorites", e.getMessage());
		}
	}
	public static int deleteFavorites(Context appContext){
		ContentProviderClient client = appContext.getContentResolver()
				.acquireContentProviderClient(
						"dk.lector.providers.FAVORITESContentProvider");
		try {
			int c = client.delete(FAVORITESContentProvider.CONTENT_URI,
					null, null);
			return c;
		} catch (RemoteException e) {
			throw new TSMobileException(e, DocDBRepository.class,
					"getFavorites", e.getMessage());
		}
	}
	public static Cursor getDocumentsBySearchID(Context appContext, int searchID) {
		ContentProviderClient client = appContext.getContentResolver()
				.acquireContentProviderClient(
						"dk.lector.providers.SearchViewContentProvider");

		try {
			Cursor c = client.query(SearchViewContentProvider.CONTENT_URI,
					null, SearchViewContentProvider.SEARCH_ID+"="+searchID, null, null);
			if (c != null) {
				Log.d("DocDBReposity - getDocumentsBySearchID", "" + c.getCount() + "   searchID recieved: " + searchID);
			}
			return c;
		} catch (RemoteException e) {
			throw new TSMobileException(e, DocDBRepository.class,
					"getDocumentsBySearchID()", e.getMessage());
		}
	}

	public static Cursor getDocumentByID(Context baseContext, int documentID) {
		ContentProviderClient client = baseContext.getContentResolver()
				.acquireContentProviderClient(
						"dk.lector.providers.CACHEDDOC_VIEWContentProvider");

		try {
			Cursor c = client.query(CACHEDDOC_VIEWContentProvider.CONTENT_URI,
					null, CACHEDDOC_VIEWContentProvider._ID+"="+documentID, null, null);
			if (c != null) {
				Log.d("DocDBReposity - getDocumentByID", "" + c.getCount() + "   docID recieved: " + documentID);
			}
			return c;
		} catch (RemoteException e) {
			throw new TSMobileException(e, DocDBRepository.class,
					"getDocumentByID()", e.getMessage());
		}
	}


	public static void updateOrInsertDocMetaData(Context baseContext,
			ContentValues docmetavalues) {
		ContentProviderClient client = baseContext.getContentResolver()
				.acquireContentProviderClient(
						baseContext.getString(R.string.doc_meta_authority));

		
		try {
			if( client.query(DOC_METADATAContentProvider.CONTENT_URI, null, DOC_METADATAContentProvider._ID+"="+docmetavalues.getAsInteger(DOC_METADATAContentProvider._ID), null, null).getCount() == 0){
				client.insert(DOC_METADATAContentProvider.CONTENT_URI, docmetavalues);
				Log.d("updateOrInsertDocMetaData", "insert");
			} else {
				client.update(DOC_METADATAContentProvider.CONTENT_URI, docmetavalues, DOC_METADATAContentProvider._ID+"="+docmetavalues.getAsInteger(DOC_METADATAContentProvider._ID), null);
				Log.d("updateOrInsertDocMetaData", "update");
			}
			
			
		} catch (RemoteException e) {
			throw new TSMobileException(e, DocDBRepository.class,
					"createSearch()", e.getMessage());
		}

		
	}

	public static void updateOrInsertStoredDocData(Context baseContext,
			ContentValues docstoredvalues) {
		ContentProviderClient client = baseContext.getContentResolver()
				.acquireContentProviderClient(
						baseContext.getString(R.string.doc_stored_authority));

		try {
			if( client.query(DOC_STOREDContentProvider.CONTENT_URI, null, DOC_STOREDContentProvider._ID+"="+docstoredvalues.getAsInteger(DOC_STOREDContentProvider._ID), null, null).getCount() == 0){
				client.insert(DOC_STOREDContentProvider.CONTENT_URI, docstoredvalues);
				Log.d("updateOrInsertStoredDocData", "insert");
			} else {
				client.update(DOC_STOREDContentProvider.CONTENT_URI, docstoredvalues, DOC_STOREDContentProvider._ID+"="+docstoredvalues.getAsInteger(DOC_STOREDContentProvider._ID), null);
				Log.d("updateOrInsertStoredDocData", "update");
			}
	
		} catch (RemoteException e) {
			throw new TSMobileException(e, DocDBRepository.class,
					"createSearch()", e.getMessage());
		}

		
	}

	public static void updateOrInsertFavorites(Context appContext,
			ContentValues favorites) {
		ContentProviderClient client = appContext.getContentResolver()
				.acquireContentProviderClient(
						appContext.getString(R.string.favorites_authority));
		try {
			if( client.query(FAVORITESContentProvider.CONTENT_URI, null, FAVORITESContentProvider.DOC_ID+"="+favorites.getAsInteger(FAVORITESContentProvider.DOC_ID), null, null).getCount() == 0){
				client.insert(FAVORITESContentProvider.CONTENT_URI, favorites);
			} else {
				client.update(FAVORITESContentProvider.CONTENT_URI, favorites, FAVORITESContentProvider.DOC_ID+"="+favorites.getAsInteger(FAVORITESContentProvider.DOC_ID), null);
			}

		} catch (RemoteException e) {
			throw new TSMobileException(e, DocDBRepository.class,
					"insertFavorites()", e.getMessage());
		}
		
	}

	public static void updateDocumentAcivity(Context baseContext,
			long timestamp, int documentID) {
		// TODO Auto-generated method stub
		
	}


	public static Cursor getLocalDocuments(Context baseContext) {
		ContentProviderClient client = baseContext.getContentResolver()
		.acquireContentProviderClient(
				"dk.lector.providers.CACHEDDOC_VIEWContentProvider");

		try {
				
			Cursor c = client.query(CACHEDDOC_VIEWContentProvider.CONTENT_URI,
			null, CACHEDDOC_VIEWContentProvider.FILE_SIZE_PERSISTET + " != 0 "+" AND " + CACHEDDOC_VIEWContentProvider.FILE_SIZE_PERSISTET + " == " + CACHEDDOC_VIEWContentProvider.FILE_SIZE, null, null);
			if (c != null) {
				Log.d("DocDBReposity - getLocalDocuments cursorCount: ", "" + c.getCount());
			}
			return c;
		} catch (RemoteException e) {
			throw new TSMobileException(e, DocDBRepository.class,
			"getLocalDocuments()", e.getMessage());
		
}
	
	}

	public static boolean deleteDocument(Context context, int documentID) {
		ContentProviderClient client = context.getContentResolver().acquireContentProviderClient(context.getString(R.string.doc_stored_authority));
		int deleted = 0;
		boolean result = false;
		try {
			Cursor pathQuery = client.query(DOC_STOREDContentProvider.CONTENT_URI, DOC_STOREDContentProvider.PROJECTION, DOC_STOREDContentProvider._ID + " == " + documentID, null, null);
			String path = pathQuery.getString(5);
			Log.d(TAG, "path to deleted file: " + path);
			
			if(FileSystemUtil.deleteSingleFile(path, context)){
			deleted = client.delete(DOC_STOREDContentProvider.CONTENT_URI, DOC_STOREDContentProvider._ID + " = " + documentID, null);
			}
			else
			return false;	
			
		} catch (RemoteException e) {
			throw new TSMobileException(e, UserDBRepository.class, "deleteDocument", "error during delete");
		}
		finally{client.release();}
		result = (deleted>0)?true:false;
		Log.d(TAG, "Singe delete result: " + deleted);
		return result;
		
	}
	
	public static boolean deleteAllDocuments(Context context) {
		
		int deleted = 0;
		int target = 0;
		boolean result = false;
		
		ContentProviderClient client = context.getContentResolver().acquireContentProviderClient(context.getString(R.string.doc_stored_authority));
		try {
			
			Cursor pathQuery = client.query(DOC_STOREDContentProvider.CONTENT_URI, null, null, null, null);
			target = pathQuery.getCount();
			Log.d(TAG, "Files cached: " + pathQuery.getCount());
			pathQuery.moveToFirst();
			
			while(!pathQuery.isAfterLast()){
			if(FileSystemUtil.deleteSingleFile(pathQuery.getString(5), context)){
			deleted += client.delete(DOC_STOREDContentProvider.CONTENT_URI, DOC_STOREDContentProvider._ID + " = " + pathQuery.getString(0), null);
			}
			pathQuery.moveToNext();
			}
			
			
		} catch (RemoteException e) {
			throw new TSMobileException(e, UserDBRepository.class, "deleteDocument", "error during delete");
		}
		finally{
		
			client.release();
			}
		result = (deleted>0 && deleted == target)?true:false;
		Log.d(TAG, "multi delete result: " + deleted);
		return result;
		
	}
	
}
